package com.mymall.serve.controller;

import com.mymall.serve.common.RootResult;
import com.mymall.serve.serviceimpl.UserServiceImpl;
import com.mymall.serve.utils.CacheUtil;
import com.mymall.serve.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotBlank;

/**
 * 用户登录
 *
 * @author weiwei
 * @since 2020-04-11 21:55
 **/
@Slf4j
@Validated
@Controller
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserServiceImpl mallUserService;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(value = "/login")
    @ResponseBody
    public RootResult<String> login(@NotBlank(message = "userName不能为空") String userName, @NotBlank(message = "password不能为空") String password){

        /*Subject subject = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password.toCharArray());
        log.info("login");
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            log.error("用户名错误",e);
            throw new BusException(ResultCodeEnum.NOT_SYS_USER);
        }catch (IncorrectCredentialsException e){
            log.error("密码错误",e);
            throw new BusException(ResultCodeEnum.ERROR_PASSWORD);
        }catch (Exception e){
            log.error("其他登录错误",e);
            throw new BusException(ResultCodeEnum.ERROR_LOGIN_EXCEPTION);
        }*/


        /*// 查询用户信息
        MallUser mallUser = mallUserService.getLoginUserByOpenId(openId);

        if (mallUser == null){
            log.error("查询用户为空");
            throw new BusException(ResultCodeEnum.NOT_SYS_USER);
        }
        // 测试角色，临时添加
        List<String> roleList = Arrays.asList("USER");
        LoginUserBO loginUserBO = new LoginUserBO(mallUser.getId(),mallUser.getWxNickName(),roleList);

        JwtPayLoad payLoad = new JwtPayLoad(mallUser.getId(),mallUser.getWxNickName());
        String token = jwtTokenUtil.generateToken(payLoad);

        // 放入当前线程中保存
        RequestThreadLocal.addUser(loginUserBO);

        // 将token对应的用户信息放入缓存供校验token使用，有效期12小时
        cacheUtil.setValue("token:" + token, JSON.toJSONString(loginUserBO), jwtTokenUtil.getExpireSeconds());

        log.info("==用户{},生成的token: {}",mallUser.getWxNickName(),token);*/
        return RootResult.success("SUCCESS");
    }
}
